import React from 'react';
import { CURRENT } from './renderAuthorize'; // eslint-disable-next-line import/no-cycle

import PromiseRender from './PromiseRender';

/**
 * 通用权限检查方法
 * Common check permissions method
 * @param { 权限判定 | Permission judgment } authority //可以是数组  string promise function
 * @param { 你的权限 | Your permission description } currentAuthority
 * @param { 通过的组件 | Passing components } target
 * @param { 未通过的组件 | no pass components } Exception
 */
const checkPermissions = (authority, currentAuthority = [], target, Exception) => {
  // 没有判定权限.默认查看所有
  // Retirement authority, return target;
  //   如果没有约定需要权限直接返回目标组件
  if (!authority) {
    return target;
  }
  //   如果没有列表权限返回未通过的组件
  if (!currentAuthority.length) {
    return Exception;
  }

  // return Exception;
  // string 处理

  if (typeof authority === 'string') {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.includes(authority)) {
        return target;
      }
    } else {
      try {
        const currentAuthorityArry = JSON.parse(currentAuthority);
        if (currentAuthorityArry.includes(authority)) {
          return target;
        }
      } catch (error) {
        return Exception;
      }
    }
    return Exception;
  }
  // Promise 处理

  if (authority instanceof Promise) {
    return <PromiseRender ok={target} error={Exception} promise={authority} />;
  } // Function 处理

  if (typeof authority === 'function') {
    try {
      const bool = authority(currentAuthority); // 函数执行后返回值是 Promise

      if (bool instanceof Promise) {
        return <PromiseRender ok={target} error={Exception} promise={bool} />;
      }

      if (bool) {
        return target;
      }

      return Exception;
    } catch (error) {
      throw error;
    }
  }

  throw new Error('unsupported parameters');
};

export { checkPermissions };

/**
 * @description 检查权限逻辑
 * @author songs
 * @date 2020-01-08
 * @param {*} authority 权限判定
 * @param {*} target 通过的组件
 * @param {*} Exception 未通过的组件
 * @returns
 */
function check(authority, target, Exception) {
  return checkPermissions(authority, CURRENT, target, Exception);
}

// 暂时没用
function permissionCheck(authorKey, target, Exception) {
  const rolePermission = [];
  return checkPermissions(rolePermission, authorKey, target, Exception);
}

export { permissionCheck };
export default check;
